package com.wbr.file.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wbr.file.pojo.Customer;
import com.wbr.file.service.CustomerService;
import com.wbr.file.utils.ExcelUtil;
import com.wbr.file.utils.JsonResult;

@Controller
@RequestMapping("/export")
public class ExcelExportController {

	@Autowired
	private CustomerService customerService;

	@RequestMapping("/excel")
	@ResponseBody
	public JsonResult exportDataToExcel(HttpServletResponse response) {

		List<Customer> customerList = new ArrayList<Customer>();

		String fileName = "顾客统计" + System.currentTimeMillis() + ".xls"; // 文件名
		String sheetName = "顾客表";

		String[] title = { "cid", "cname", "cnickname", "cjob", "caddress", "cdetail" };
		// 获取顾客列表
		try {
			customerList = customerService.getCustomerList();
		} catch (Exception e) {
			return JsonResult.build(404, "查询失败");
		}

		String[][] values = new String[customerList.size()][];
		for (int i = 0; i < customerList.size(); i++) {
			values[i] = new String[title.length];
			// 将对象内容转换成string
			Customer obj = customerList.get(i);
			values[i][0] = obj.getCid() + "";
			values[i][1] = obj.getCname();
			values[i][2] = obj.getCnickname();
			values[i][3] = obj.getCjob();
			values[i][4] = obj.getCaddress();
			values[i][5] = obj.getCdetail();
		}

		HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, values, null);

		// 将文件存放到指定位置
		try {
			this.setResponseHeader(response, fileName);
			OutputStream os = response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
			System.out.println("导出成功");
		} catch (Exception e) {
			return JsonResult.build(404, "文件导出失败！");
		}

		return JsonResult.ok();
	}
	
	@RequestMapping("/download")
	public void download(String path, HttpServletResponse response) {  
        try {  
            // path是指欲下载的文件的路径。  
            File file = new File(path);  
            // 取得文件名。  
            String filename = file.getName();  
            // 以流的形式下载文件。  
            InputStream fis = new BufferedInputStream(new FileInputStream(path));  
            byte[] buffer = new byte[fis.available()];  
            fis.read(buffer);  
            fis.close();  
            // 清空response  
            response.reset();  
            // 设置response的Header  
            response.addHeader("Content-Disposition", "attachment;filename="  
                    + new String(filename.getBytes()));  
            response.addHeader("Content-Length", "" + file.length());  
            OutputStream toClient = new BufferedOutputStream(  
                    response.getOutputStream());  
            response.setContentType("application/vnd.ms-excel;charset=gb2312");  
            toClient.write(buffer);  
            toClient.flush();  
            toClient.close();  
        } catch (IOException ex) {  
            ex.printStackTrace();  
        }  
    }  

	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
